package com.geeaks.learn.cas;

import java.lang.reflect.Field;

public class UnsafeTest {
	static class City {
		private String name = "";
		private int flag = 0;

		public City() {
			this.name = "Beijing";
			this.flag = 1;
		}

		@Override
		public String toString() {
			return name + ": " + flag;
		}

	}

	public static void main(String[] args) throws Exception {
		// 通过反射得到theUnsafe对应的Field对象
		Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
		// 设置该Field为可访问
		field.setAccessible(true);
		// 通过Field得到该Field对应的具体对象，传入null是因为该Field为static的
		sun.misc.Unsafe unsafe = (sun.misc.Unsafe) field.get(null);
		City city = (City) unsafe.allocateInstance(City.class);
		city.name = "ribensheng";
		System.out.println(city); // dont invoke constructor, print null: 0
		City anotherCity = new City();
		System.out.println(anotherCity); // print Beijing: 1
	}
}
